
package com.hlkj.pay.app.merchant.ext.impl.gtzfpay.ext;
/*
 * Hlpay-Plus aggregate payment system.
 * Copyright (c) 2024-2025 Hlpay Team Copyright has the right of final interpretation.
 */

import cn.hutool.core.date.DatePattern;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.hlkj.framework.common.pojo.CommonResult;
import com.hlkj.framework.common.util.json.JsonUtils;
import com.hlkj.framework.extension.annotation.Extension;
import com.hlkj.pay.app.merchant.ext.dto.order.ChannelPayOrderContext;
import com.hlkj.pay.app.merchant.ext.dto.order.ChannelPayOrderQueryContext;
import com.hlkj.pay.app.merchant.ext.dto.order.ChannelRefundPayOrderContext;
import com.hlkj.pay.app.merchant.ext.impl.gtzfpay.GtzfScenePayOrderExtPt;
import com.hlkj.pay.app.merchant.ext.impl.gtzfpay.constant.GtzfPayConstant;
import com.hlkj.pay.app.merchant.ext.impl.gtzfpay.constant.GtzfPayExtConstant;
import com.hlkj.pay.app.merchant.ext.impl.gtzfpay.dto.GtzfPayConfig;
import com.hlkj.pay.app.merchant.ext.impl.gtzfpay.dto.GtzfpayAppChannelParams;
import com.hlkj.pay.app.merchant.ext.impl.gtzfpay.utils.GtzfPayRsaUtil;
import com.hlkj.pay.app.merchant.ext.impl.gtzfpay.utils.HttpUtils;
import com.hlkj.pay.infrastructure.model.merchant.MerchantAppChannelDO;
import com.hlkj.pay.infrastructure.model.order.PayOrderDO;
import com.hlkj.pay.infrastructure.model.pay.ProviderChannelConfigDO;
import com.hlkj.pay.util.DateUtils;
import com.hlkj.pay.util.MerchantUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Repository;
import org.springframework.util.StringUtils;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * 主扫统一下单 用户扫支付码
 *
 * @author HlpayTeam
 * @date 2024/11/18 13:07
 */
@Slf4j
@Repository
@RequiredArgsConstructor
@Extension(bizId = GtzfPayExtConstant.NATIVE_PAY)
public class GtzfPayScanPayOrderExtPt extends GtzfPaySceneCommonPayOrder implements GtzfScenePayOrderExtPt {

    @Value("${hlkj.domain}")
    private String domain;

    @Override
    public void submitChannelPayOrder(ChannelPayOrderContext channelPayOrderContext) {
        other(channelPayOrderContext);
    }

    private void other(ChannelPayOrderContext channelPayOrderContext) {
        ProviderChannelConfigDO providerChannelConfigDO = channelPayOrderContext.getProviderChannelConfigDO();
        String channelConfig = providerChannelConfigDO.getParamsConfig();
        // 配置转换
        GtzfPayConfig config = JsonUtils.parseObject(channelConfig, GtzfPayConfig.class);
        PayOrderDO payOrderDO = channelPayOrderContext.getPayOrderDO();
        MerchantAppChannelDO merchantAppChannelDO = channelPayOrderContext.getMerchantAppChannelDO();

        try {
            //国通需回调地址要替换成映射地址
            channelPayOrderContext.setNotifyUrl(channelPayOrderContext.getNotifyUrl().replace(domain, config.getCallbackDomain()));

            GtzfpayAppChannelParams appChannelParams = easyPayAppChannelParams(merchantAppChannelDO, config);
            Map<String, String> map = new LinkedHashMap<>();
            map.put("agetId", config.getAgetId());
            map.put("custId", appChannelParams.getCustId());
            map.put("orderNo", payOrderDO.getPayOrderNo());
            map.put("txamt", MerchantUtils.YuanToFen(payOrderDO.getAmount()).toString());
            map.put("payChannel", "1");
            if ("ALIPAY".equals(payOrderDO.getPayType())) {
                map.put("payChannel", "1");
            } else if ("UNION_APY".equals(payOrderDO.getPayType())) {
                map.put("payChannel", "9");
            }
            if (StringUtils.hasText(appChannelParams.getPayIp())) {
                map.put("ip", appChannelParams.getPayIp());
            } else
                map.put("ip", payOrderDO.getClientIp());
            map.put("version", "1.0.0");
            map.put("timeStamp", DateUtils.getDateString(DatePattern.PURE_DATETIME_PATTERN));
            map.put("asyncNotify", channelPayOrderContext.getNotifyUrl());
            String sign = GtzfPayRsaUtil.encrypt(GtzfPayRsaUtil.getContent(JSONUtil.parseObj(map)), config.getMchPublicKey());
            map.put("sign", sign);

            String url = domain(channelPayOrderContext.isTest()) + GtzfPayConstant.TRADE_NATIVE;
            log.info("国通支付宝扫码统一下单req参数:{}", JsonUtils.toJsonString(map));
            String response = HttpUtils.post(url, JsonUtils.toJsonString(map));
            log.info("国通支付宝扫码统一下单返回参数:{}", response);

            JSONObject rspBody = JsonUtils.parseObj(response);
            if ("000000".equals(rspBody.getStr("code"))) {
                JSONObject respStateInfo = rspBody.getJSONObject("data");
                channelPayOrderContext.setInsOrderNo(respStateInfo.getStr("orderNo"));

                channelPayOrderContext.setPayDataType("url");
                channelPayOrderContext.setPayInfo(respStateInfo.getStr("url"));
            } else {
                String respDesc = rspBody.getStr("msg");
                channelPayOrderContext.setProcessStatus(Boolean.FALSE);
                if (StringUtils.hasText(respDesc)) {
                    channelPayOrderContext.setRemark(respDesc);
                } else {
                    channelPayOrderContext.setRemark("国通提交支付宝扫码统一下单查询返回错误信息为空,错误码为:" + rspBody.getStr("code"));
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("国通提交支付宝扫码统一下单请求失败 message:{}", e.getMessage(), e);
            channelPayOrderContext.setRemark("国通提交支付宝扫码统一下单请求失败,失败信息" + e.getMessage());
            channelPayOrderContext.setProcessStatus(Boolean.FALSE);
        }
    }

    private void createOrder(ChannelPayOrderContext channelPayOrderContext) {
        ProviderChannelConfigDO providerChannelConfigDO = channelPayOrderContext.getProviderChannelConfigDO();
        String channelConfig = providerChannelConfigDO.getParamsConfig();
        // 配置转换
        GtzfPayConfig config = JsonUtils.parseObject(channelConfig, GtzfPayConfig.class);
        PayOrderDO payOrderDO = channelPayOrderContext.getPayOrderDO();
        MerchantAppChannelDO merchantAppChannelDO = channelPayOrderContext.getMerchantAppChannelDO();

        try {
            GtzfpayAppChannelParams appChannelParams = easyPayAppChannelParams(merchantAppChannelDO, config);

            Map<String, String> map = new LinkedHashMap<>();
            map.put("agetId", config.getAgetId());
            map.put("custId", appChannelParams.getCustId());
            map.put("orderNo", payOrderDO.getPayOrderNo());
            map.put("txamt", MerchantUtils.YuanToFen(payOrderDO.getAmount()).toString());
            map.put("payType", "01");
            map.put("outTime", expireMinute(payOrderDO.getExpiredTime()).toString());
            map.put("remark", payOrderDO.getSubject());
            map.put("version", "1.0.0");
            map.put("timeStamp", DateUtils.getDateString(DatePattern.PURE_DATETIME_PATTERN));
            map.put("asyncNotify", channelPayOrderContext.getNotifyUrl());
            String sign = GtzfPayRsaUtil.encrypt(GtzfPayRsaUtil.getContent(JSONUtil.parseObj(map)), config.getMchPublicKey());
            map.put("sign", sign);

            String url = domain(channelPayOrderContext.isTest()) + GtzfPayConstant.TRADE_DEFAULT_NATIVE;
            log.info("国通扫码统一下单req参数:{}", JsonUtils.toJsonString(map));
            String response = HttpUtils.post(url, JsonUtils.toJsonString(map));
            log.info("国通扫码统一下单返回参数:{}", response);

            JSONObject rspBody = JsonUtils.parseObj(response);
            if ("000000".equals(rspBody.getStr("code"))) {
                JSONObject respStateInfo = rspBody.getJSONObject("data");
                channelPayOrderContext.setInsOrderNo(respStateInfo.getStr("orderNo"));

                channelPayOrderContext.setPayDataType("url");
                channelPayOrderContext.setPayInfo(respStateInfo.getStr("url"));
            } else {
                String respDesc = rspBody.getStr("msg");
                channelPayOrderContext.setProcessStatus(Boolean.FALSE);
                if (StringUtils.hasText(respDesc)) {
                    channelPayOrderContext.setRemark(respDesc);
                } else {
                    channelPayOrderContext.setRemark("国通提交扫码统一下单查询返回错误信息为空,错误码为:" + rspBody.getStr("code"));
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("国通提交扫码统一下单请求失败 message:{}", e.getMessage(), e);
            channelPayOrderContext.setRemark("国通提交扫码统一下单请求失败,失败信息" + e.getMessage());
            channelPayOrderContext.setProcessStatus(Boolean.FALSE);
        }
    }

    @Override
    public void queryChannelPayOrder(ChannelPayOrderQueryContext channelPayOrderQueryContext) {
        commonQueryChannelPayOrder(channelPayOrderQueryContext);
    }

    @Override
    public void closeChannelPayOrder(ChannelPayOrderQueryContext channelPayOrderQueryContext) {
        commonCloseChannelPayOrder(channelPayOrderQueryContext);
    }

    @Override
    public void queryChannelClosePayOrder(ChannelPayOrderQueryContext channelPayOrderQueryContext) {
        commonQueryChannelClosePayOrder(channelPayOrderQueryContext);
    }

    @Override
    public void refundChannelPayOrder(ChannelRefundPayOrderContext channelRefundPayOrderContext) {
        commonRefundChannelPayOrder(channelRefundPayOrderContext);
    }

    @Override
    public void queryRefundChannelPayOrder(ChannelRefundPayOrderContext channelRefundPayOrderContext) {
        commonQueryRefundChannelPayOrder(channelRefundPayOrderContext);
    }

    @Override
    public boolean refundApply(ChannelRefundPayOrderContext channelRefundPayOrderContext) {
        return true;
    }

    @Override
    public CommonResult<String> channelOrderCode(ChannelPayOrderContext channelPayOrderContext) {
        return CommonResult.success();
    }
}
